﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using QModels;
using QServices;
using QServices.Services;
using Quartz;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace QQPlcPlayer.ViewModel
{
	public partial class MainWindowViewModel : ObservableObject
	{

		[ObservableProperty]
		private string nowTime;
		[ObservableProperty]
		private string firstTime;
		[ObservableProperty]
		private string secondTime;
		[ObservableProperty]
		private string thirdTime;

		[ObservableProperty]
		private int first_80;
		[ObservableProperty]
		private int second_80;
		[ObservableProperty]
		private int third_80;
		[ObservableProperty]
		private int first_120;
		[ObservableProperty]
		private int second_120;
		[ObservableProperty]
		private int third_120;
		[ObservableProperty]
		private int first_160;
		[ObservableProperty]
		private int second_160;
		[ObservableProperty]
		private int third_160;
		[ObservableProperty]
		private int first_200;
		[ObservableProperty]
		private int second_200;
		[ObservableProperty]
		private int third_200;
		[ObservableProperty]
		private int hourFirst;
		[ObservableProperty]
		private int minuteFirst;
		[ObservableProperty]
		private int hourSecond;
		[ObservableProperty]
		private int minuteSecond;
		[ObservableProperty]
		private int hourThird;
		[ObservableProperty]
		private int minuteThird;
		[ObservableProperty]
		private string ip;
		[ObservableProperty]
		private decimal? maxElectricQty;
		[ObservableProperty]
		private decimal? minAllowEleQty;
		[ObservableProperty]
		private decimal currentElectricQty;



		[ObservableProperty]
		private bool isCheckAuto;


		[ObservableProperty]
		private string currentBarCode;

		[ObservableProperty]
		private string currentFeedArray;

		public DateTime first_Time => DateTime.Parse($"{HourFirst}:{MinuteFirst}:00");
		public DateTime second_Time => DateTime.Parse($"{HourSecond}:{MinuteSecond}:00");
		public DateTime third_Time => DateTime.Parse($"{HourThird}:{MinuteThird}:00");
		public DispatcherTimer m_autoTimer;

		public AlarmHelper FeedAlarm { get; set; }
		public AlarmHelper ChongDianAlarm { get; set; }
        public AlarmHelper StationAlarm { get; set; }
        /// <summary>
        /// 5分钟定时器
        /// </summary>
        private DispatcherTimer station_dispatcherTimer;
        public MainWindowViewModel()
		{
			nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
			InitFeedTime();
			var feedpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "videos", "喂料中注意避让.mp3");
			var chongdianpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "videos", "充电中请注意.mp3");
            var Stationpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "videos", "加料异常.mp3");
            FeedAlarm = new AlarmHelper(feedpath);
			ChongDianAlarm = new AlarmHelper(chongdianpath);
            StationAlarm = new AlarmHelper(Stationpath);
            // 初始化定时器，设置间隔为5分钟（300,000 毫秒）
            station_dispatcherTimer = new DispatcherTimer();
            station_dispatcherTimer.Tick += Main_StationTimer_Tick;
            station_dispatcherTimer.Interval = new TimeSpan(0, 5, 0);
            station_dispatcherTimer.Start();
        }
        private void Main_StationTimer_Tick(object? sender, EventArgs e)
        {
            Alarm_sattion();
        }
        public void Alarm_sattion()
        {
            var Plc = AppRuntime.GetPlcManager().GetPlc();
            var stationL1 = Plc.Read("DB1000.DBX162.1");
            var stationL2 = Plc.Read("DB1000.DBX162.2");
            var stationL3 = Plc.Read("DB1000.DBX162.3");
            var stationL4 = Plc.Read("DB1000.DBX162.4");
            var stationL5 = Plc.Read("DB1000.DBX120.7");
            if (Convert.ToBoolean(stationL2) == false || Convert.ToBoolean(stationL4) == false)
            {
                StationAlarm.StopAlarm();
                StationAlarm.StartAlarm();
            }
            if (Convert.ToBoolean(stationL5) == false)
            {
                StationAlarm.StopAlarm();
                StationAlarm.StartAlarm();
            }
            var ServoStatus_F1 = (byte)Plc.Read(DataType.DataBlock, 1000, 121, VarType.Byte, 1);
            var ServoStatus_F2 = (byte)Plc.Read(DataType.DataBlock, 1000, 122, VarType.Byte, 1);
            var ServoStatus_F3 = (byte)Plc.Read(DataType.DataBlock, 1000, 123, VarType.Byte, 1);
            var ServoStatus_F4 = (byte)Plc.Read(DataType.DataBlock, 1000, 124, VarType.Byte, 1);

            string hexValueF1 = Convert.ToString(ServoStatus_F1, 16).ToUpper();
            string hexValueF2 = Convert.ToString(ServoStatus_F2, 16).ToUpper(); // 结果为 "FE"
            string hexValueF3 = Convert.ToString(ServoStatus_F3, 16).ToUpper(); // 结果为 "FE"
            string hexValueF4 = Convert.ToString(ServoStatus_F4, 16).ToUpper(); // 结果为 "FE"
			//var carstatus = tt.WeiLiaoZhong ;
			if (hexValueF1.Contains("FE")
				&& hexValueF2.Contains("FE")
                && hexValueF3.Contains("FE")
                && hexValueF4.Contains("FE"))
			{
				// 创建一个计时器，用于延迟20分钟后再执行特定的方法。
				var timer = new System.Threading.Timer(CheckStationsAfterDelay, new Tuple<object, object>(stationL1, stationL3),
			   TimeSpan.FromMinutes(20), Timeout.InfiniteTimeSpan); // 不重复触发 // 延迟20分钟


				if (Convert.ToBoolean(stationL1) == false || Convert.ToBoolean(stationL3) == false)
				{
                    StationAlarm.StopAlarm();
                    StationAlarm.StartAlarm();
				}
			}
		}
        private void CheckStationsAfterDelay(object state)
        {
            // 解包传入的状态对象。
            var stations = (Tuple<object, object>)state;

            // 重新获取PLC实例，以确保是最新的连接。
            var plc = AppRuntime.GetPlcManager().GetPlc();

            // 由于20分钟前读取的状态可能已经过时，因此在延迟结束后再次读取最新的PLC状态。
            var stationL1 = plc.Read("DB1000.DBX162.1");
            var stationL3 = plc.Read("DB1000.DBX162.3");

            // 如果在延迟结束后的任一时刻stationL1或stationL3为false，则启动报警。
            if (Convert.ToBoolean(stationL1) == false || Convert.ToBoolean(stationL3) == false)
            {
                StationAlarm.StartAlarm();
            }
        }
        public void InitFeedTime()
		{
			var car = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarByNumber(AppRuntime.CarNumber);
			var schedule = AppRuntime.GetService().GetService<DosingScheduleService>().GetDosingScheduleByCarId(car.ID);
			FirstTime = $"{schedule.HourFirst}:{schedule.MinuteFirst}";
			SecondTime = $"{schedule.HourSecond}:{schedule.MinuteSecond}";
			ThirdTime = $"{schedule.HourThird}:{schedule.MinuteThird}";
			HourFirst = schedule.HourFirst;
			HourSecond = schedule.HourSecond;
			HourThird = schedule.HourThird;
			MinuteFirst = schedule.MinuteFirst;
			MinuteSecond = schedule.MinuteSecond;
			MinuteThird = schedule.MinuteThird;
			Ip = car.IP;
			MaxElectricQty = car.MaxElectricQty;
			MinAllowEleQty = car.MinAllowEleQty;

			First_80 = schedule.First_80;
			Second_80 = schedule.Second_80;
			Third_80 = schedule.Third_80;
			First_120 = schedule.First_120;
			Second_120 = schedule.Second_120;
			Third_120 = schedule.Third_120;
			First_160 = schedule.First_160;
			Second_160 = schedule.Second_160;
			Third_160 = schedule.Third_160;
			First_200 = schedule.First_200;
			Second_200 = schedule.Second_200;
			Third_200 = schedule.Third_200;

			IsCheckAuto = car.IsAutomatic;
			if (IsCheckAuto && m_autoTimer == null) OpenAutoFeed(true);
			AppRuntime.AgvCar = car;
		}



		[RelayCommand]
		public void SaveOtherSetting()
		{

			if (string.IsNullOrWhiteSpace(Ip))
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "请输入正确的ip",
					WaitTime = 6,
					IsCustom = true,

				});
				return;
			}
			if (MaxElectricQty <= 0 || MinAllowEleQty <= 0 || MaxElectricQty < MinAllowEleQty)
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "输入的最大电量和最小启动电量必须大于0且满量不能小于启动电量",
					WaitTime = 6,
					IsCustom = true,

				});
				return;
			}



			var res = AppRuntime.GetService().GetService<AgvCarService>().UpdateCarPlcOtherSetting(AppRuntime.CarNumber, Ip, MaxElectricQty, MinAllowEleQty);
			if (res)
			{
				Growl.SuccessGlobal("保存成功!");
				AppRuntime.Logger_Info("保存小车IP/MaxElectricQty/MinAllowEleQty成功");
			}
			else
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "保存失败",

					IsCustom = true,
				});
				AppRuntime.Logger_Error("保存小车IP/MaxElectricQty/MinAllowEleQty失败");
			}

		}
		[RelayCommand]
		public void SaveScheduleTime()
		{
			var res = AppRuntime.GetService().GetService<DosingScheduleService>().UpdateDosingScheduleTime(HourFirst, HourSecond, HourThird, MinuteFirst, MinuteSecond, MinuteThird);
			if (res)
			{
                AppRuntime.InitQu();
                Growl.SuccessGlobal("保存成功!");
				AppRuntime.Logger_Info("保存喂料时间成功");
			}
			else
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "保存失败",

				});
				AppRuntime.Logger_Error("保存喂料时间失败");
			}
			InitFeedTime();
		}
		[RelayCommand]
		public void SaveScheduleFeed()
		{
			var array = new int[12];


			array[0] = First_80;
			array[1] = Second_80;
			array[2] = Third_80;
			array[3] = First_120;
			array[4] = Second_120;
			array[5] = Third_120;
			array[6] = First_160;
			array[7] = Second_160;
			array[8] = Third_160;
			array[9] = First_200;
			array[10] = Second_200;
			array[11] = Third_200;

			var isok = true;
			var msg = "";
			//80  120  160  200
			//0    1    2    3
			//0    3    6    9
			for (int i = 0; i < 4; i++)
			{
				var sum = array[i * 3] + array[i * 3 + 1] + array[i * 3 + 2];
				var ok = i * 40 + 80;
				if (sum != ok)
				{
					isok = false;
					msg = $"第{i + 1}行数据之和应该为:{ok}";
					break;
				}
				if (array[i * 3] % 40 != 0 || array[i * 3 + 1] % 40 != 0 || array[i * 3 + 2] % 40 != 0)
				{
					isok = false;
					msg = $"第{i + 1}行数据必须是40的倍数";
					break;
				}
			}
			if (!isok)
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = msg,
					IsCustom = true,
				});
				AppRuntime.Logger_Error(msg);
				return;
			}



			var res = AppRuntime.GetService().GetService<DosingScheduleService>().UpdateDosingScheduleFeed(array);
			if (res)
			{
				Growl.SuccessGlobal("保存成功!");
				AppRuntime.Logger_Info("保存喂料量成功");
			}
			else
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "保存失败",

					IsCustom = true,
				});
				AppRuntime.Logger_Error("保存喂料量失败");
			}
			InitFeedTime();
		}

		[RelayCommand]
		public void OpenAutoFeed(bool ischeck)
		{
			if (ischeck)//开启
			{
				if (m_autoTimer == null)
				{
					m_autoTimer = new DispatcherTimer(DispatcherPriority.Background);
					m_autoTimer.Interval = new TimeSpan(0, 0, 1);
				}
				m_autoTimer.Tick -= AutoFeedHandler;
				m_autoTimer.Tick += AutoFeedHandler;

				Growl.SuccessGlobal("开启自动喂料成功!");
				AppRuntime.Logger_Info("开启自动喂料成功");
			}
			else//关闭
			{
				m_autoTimer.Stop();
				m_autoTimer.Tick -= AutoFeedHandler;
				Growl.SuccessGlobal("关闭自动喂料成功!");
				AppRuntime.Logger_Info("关闭自动喂料成功");
			}
		}

		/// <summary>
		/// 自动喂料的逻辑
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AutoFeedHandler(object? sender, EventArgs e)
		{
			if (!IsCheckAuto) return;

			m_autoTimer.IsEnabled = false;
			var isfirst = DateTime.Now >= first_Time && DateTime.Now < second_Time;
			if (isfirst)
			{
				AutoFeedEvenyTimePlus(isfirst, false, false);
				m_autoTimer.IsEnabled = true;
				return;
			}
			var issecond = DateTime.Now >= second_Time && DateTime.Now < third_Time;
			if (issecond)
			{
				AutoFeedEvenyTimePlus(false, true, false);
				m_autoTimer.IsEnabled = true;
				return;
			}
			var isthird = DateTime.Now >= third_Time;
			if (isthird)
			{
				AutoFeedEvenyTimePlus(false, false, true);
				m_autoTimer.IsEnabled = true;
				return;
			}
			m_autoTimer.IsEnabled = true;


		}

		public AgvFeedCupModel BeforeAgvFeedCupModel { get; set; }

		private void AutoFeedEvenyTimePlus(bool IsFirst, bool IsSecond, bool IsThird)
		{
			var barcode = "";
			try
			{
				barcode = AppRuntime.GetPlcManager().GetBarCode();
				if (string.IsNullOrWhiteSpace(barcode)) return;
				if (!AppRuntime.TodayDosingSchedule.OKSchedues.ContainsKey(barcode)) return;

			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = $"上位机读取二维码失败",
					IsCustom = true,
				});
				AppRuntime.Logger_Error(ex);
			}

			var values = AppRuntime.GetCurrentBatCodeFeed(barcode, IsFirst, IsSecond, IsThird);
			CurrentBarCode = barcode;
			CurrentFeedArray = $"[{string.Join(',', values)}]";
			var tt = AppRuntime.GetPlcManager().GetGVCarStatusModel();
			var FeedNumber = 1; if (IsSecond) FeedNumber = 2; if (IsThird) FeedNumber = 3;
			tt.FeedNumber = FeedNumber;
			tt.Id = Guid.NewGuid();
			tt.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
			tt.BarCode = barcode;
			tt.FeedTotal = CurrentFeedArray;
			try
			{
				if (IsFirst && AppRuntime.FirstFeedCache.Contains(barcode)) return;
				if (IsSecond && AppRuntime.SecondFeedCache.Contains(barcode)) return;
				if (IsThird && AppRuntime.ThirdFeedCache.Contains(barcode)) return;
				
				var cupsInfo = AppRuntime.GetCurrentCups();
				AppRuntime.InteractionPLCByQ(values, barcode, FeedNumber);
				var TotalCupNumbers = new int[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
				var ThisCupNumber = new int[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
				#region 杯数
				TotalCupNumbers[0] = cupsInfo.L1;
				TotalCupNumbers[1] = cupsInfo.L2;
				TotalCupNumbers[2] = cupsInfo.L3;
				TotalCupNumbers[3] = cupsInfo.L4;
				TotalCupNumbers[5] = cupsInfo.R1;
				TotalCupNumbers[6] = cupsInfo.R2;
				TotalCupNumbers[7] = cupsInfo.R3;
				if (BeforeAgvFeedCupModel != null && cupsInfo != null)
				{
					ThisCupNumber[0] = cupsInfo.L1 - BeforeAgvFeedCupModel.L1;
					ThisCupNumber[1] = cupsInfo.L2 - BeforeAgvFeedCupModel.L2;
					ThisCupNumber[2] = cupsInfo.L3 - BeforeAgvFeedCupModel.L3;
					ThisCupNumber[3] = cupsInfo.L4 - BeforeAgvFeedCupModel.L4;
					ThisCupNumber[4] = cupsInfo.R1 - BeforeAgvFeedCupModel.R1;
					ThisCupNumber[5] = cupsInfo.R2 - BeforeAgvFeedCupModel.R2;
					ThisCupNumber[6] = cupsInfo.R3 - BeforeAgvFeedCupModel.R3;
					ThisCupNumber[7] = cupsInfo.R4 - BeforeAgvFeedCupModel.R4;
				}

				BeforeAgvFeedCupModel = cupsInfo;
				tt.ThisCupNumber = $"[{string.Join(',', ThisCupNumber)}]";
				tt.TotalCupNumbers = $"[{string.Join(',', TotalCupNumbers)}]";
				#endregion



			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = $"上位机写入喂料量失败",
					WaitTime = 6,
					IsCustom = true,
				});
				AppRuntime.Logger_Error(ex);

			}

			try
			{
				if (IsFirst && !AppRuntime.FirstFeedCache.Contains(barcode)) AppRuntime.FirstFeedCache.Add(barcode);
				if (IsSecond && !AppRuntime.SecondFeedCache.Contains(barcode)) AppRuntime.SecondFeedCache.Add(barcode);
				if (IsThird && !AppRuntime.ThirdFeedCache.Contains(barcode)) AppRuntime.ThirdFeedCache.Add(barcode);
			}
			catch (Exception ex)
			{

			}
			if (tt.ServoUseStatus != 255 || true)
			{
				try
				{
					AppRuntime.GetService().GetService<AgvCarService>().AddAGVCarStatusModel2DB(tt);
				}
				catch (Exception ex)
				{
					AppRuntime.Logger_Error(ex);
					//SqliteDBHelper.InitDB_Table();
				}

			}

		}

		public void UpdateCarElectricLimit()
		{
			var car = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarByNumber(AppRuntime.CarNumber);
			if (car != null)
			{
				var minQty = (int)car.MinAllowEleQty.Value;
				var maxQty = (int)car.MaxElectricQty.Value;
				AppRuntime.GetPlcManager().UpdateCarMaxMinElectricQty(minQty, maxQty);
			}
		}

		public void InitAutoFeedTimer()
		{



			if (CurrentElectricQty < MinAllowEleQty)
			{
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = $"当前电量为:{CurrentElectricQty},低于允许启动电量:{MinAllowEleQty}",
					WaitTime = 6,
					IsCustom = true,
				});
				AppRuntime.Logger_Error($"当前电量为:{CurrentElectricQty},低于允许启动电量:{MinAllowEleQty}");
				return;
			}
			InitDataForPLC();
			Task.Run(() =>
			{
				try
				{
					AppRuntime.GetPlcManager().上位机下达允许喂料(false);
					Task.Delay(1000 * 5);
					AppRuntime.GetPlcManager().上位机下达允许喂料(true);
				}
				catch (Exception ex)
				{
					AppRuntime.Logger_Error(ex);
					Growl.ErrorGlobal(new GrowlInfo
					{
						Message = $"上位机下达允许喂料失败",
						WaitTime = 6,
						IsCustom = true,
					});
					AppRuntime.Logger_Error(ex);

				}


			});

			if (m_autoTimer == null)
			{
				m_autoTimer = new DispatcherTimer(DispatcherPriority.Background);
				m_autoTimer.Interval = new TimeSpan(0, 0, 1);
			}
			m_autoTimer.Tick -= AutoFeedHandler;
			m_autoTimer.Tick += AutoFeedHandler;
			if (m_autoTimer.IsEnabled) m_autoTimer.Stop();

			m_autoTimer.Start();

			FeedAlarm.StartAlarm();
		}





		[RelayCommand]
		public void OpenPlc()
		{

			try
			{
				AppRuntime.GetPlcManager().GetPlc().Open();
				Growl.SuccessGlobal("打开plc成功!");
				InitDataForPLC();
			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "打开plc失败",
					WaitTime = 6,
					IsCustom = true,
				});
				AppRuntime.Logger_Error(ex);
			}



		}
		[RelayCommand]
		public void ClosePlc()
		{

			try
			{
				AppRuntime.GetPlcManager().GetPlc().Close();
				Growl.SuccessGlobal("关闭plc成功!");
			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "关闭plc失败",
					WaitTime = 6,
					IsCustom = true,
				});
			}
		}

		[RelayCommand]
		public void StarFeed()
		{
			try
			{
				AppRuntime.GetPlcManager().上位机下达允许喂料(true);
				Growl.SuccessGlobal("上位机下达允许喂料成功!");
			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "上位机下达允许喂料失败",
					WaitTime = 6,
					IsCustom = true,
				});
			}
		}

		[RelayCommand]
		public void StopFeed()
		{
			try
			{
				AppRuntime.GetPlcManager().上位机下达允许喂料(false);
				Growl.SuccessGlobal("上位机下达停止喂料成功!");
			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "上位机下达停止喂料失败",
					WaitTime = 6,
					IsCustom = true,
				});
			}
		}

		[RelayCommand]
		public void ReadBarCode()
		{
			try
			{
				InitDataForPLC();
				var res = AppRuntime.GetPlcManager().GetBarCode();//"A0300201-0000-0000-0000-000000000000";//
				CurrentBarCode = res;
				Growl.SuccessGlobal("上位机读取二维码成功!");
				var isfirst = DateTime.Now >= first_Time && DateTime.Now < second_Time;
				var issecond = DateTime.Now >= second_Time && DateTime.Now < third_Time;

				var isthird = DateTime.Now >= third_Time;
				var values = AppRuntime.GetCurrentBatCodeFeed(res, isfirst, issecond, isthird);
				CurrentFeedArray = $"[{string.Join(',', values)}]";
			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error(ex);
				Growl.ErrorGlobal(new GrowlInfo
				{
					Message = "上位机读取二维码失败",
					IsCustom = true,
				});
				AppRuntime.Logger_Error(ex);
			}
		}
		[RelayCommand]
		public void SetFeedData()
		{
			var isfirst = DateTime.Now >= first_Time && DateTime.Now < second_Time;
			var issecond = DateTime.Now >= second_Time && DateTime.Now < third_Time;
			var isthird = DateTime.Now >= third_Time;
			var barcode = AppRuntime.GetPlcManager().GetBarCode();
			var values = AppRuntime.GetCurrentBatCodeFeed(barcode, isfirst, issecond, isthird);
			AppRuntime.InteractionPLCByQ(values, barcode);
			Growl.SuccessGlobal("写入喂料量成功!");
		}


		public void InitDataForPLC()
		{
			AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarAndDosingScheduleFromRemote();
			AppRuntime.InitFeedRate();
			AppRuntime.GetDosingScheduleAndUpdate();
			AppRuntime.TodayDosingSchedule = AppRuntime.GetService().GetService<DosingScheduleService>().GetTodayDosingScheduleByQ();
		}


		public void UpdateCarMaxMinElectricQty(int minQty, int maxQty)
		{
			AppRuntime.GetPlcManager().UpdateCarMaxMinElectricQty(minQty, maxQty);
			AppRuntime.AgvCar = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarByNumber(AppRuntime.CarNumber);
		}


		public async Task UpdateChongDianTask()
		{
			var schedule = await AppRuntime.SchedulerFactory.GetScheduler();
			var trigger = await schedule.GetTrigger(new TriggerKey("CarElectricJobTrigger", "AGV"));
			if (trigger != null)
			{
				var agv = AppRuntime.GetService().GetService<AgvCarService>().GetAgvCarByNumber(AppRuntime.CarNumber);
				if (agv != null)
				{
					if (AppRuntime.IsDebug)
					{
						var tt = DateTime.Now.AddMinutes(1);
						var hour = tt.Hour;
						var minute = tt.Minute;
						var newtrigger = trigger.GetTriggerBuilder().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(hour, minute)).Build();
						await schedule.RescheduleJob(trigger.Key, newtrigger);
					}
					else
					{
						var newtrigger = trigger.GetTriggerBuilder().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(agv.TaskHour, agv.TaskMinute)).Build();
						await schedule.RescheduleJob(trigger.Key, newtrigger);

					}

					if (!schedule.IsStarted)
					{
						await schedule.Start();
					}
				}

			}
		}











	}
}
